<template>
    <div>
        <el-tabs v-model="activeName" @tab-click="switchTabPane">
            <el-tab-pane :label="$t('exempt.title')+$t('exempt.operation.applicationSwitchSetting')" name="left"></el-tab-pane>
            <el-tab-pane :label="$t('exempt.title')+$t('exempt.operation.applicationFormMaintenance')" name="right"></el-tab-pane>
        </el-tabs>
        <el-card>
            <template v-if="activeName == 'left'">
                <h1 slot="header">{{$t('exempt.operation.openPermissions')}}</h1>
                <el-form
                    ref="settingForm"
                    :rules="settingFormRule"
                    :model="settingForm"
                    label-position="right"
                    label-width="90px"
                >
                    <el-row>
                        <el-col :span="7">
                            <el-form-item :label="$t('label.schoolTerm')+'：'" prop="calendarId">
                                <calendar-select v-model="settingForm.calendarId" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.beginTime')+'：'" prop="startTime">
                                <el-date-picker
                                    type="datetime"
                                    :placeholder="$t('message.plzSelect')"
                                    style="100%"
                                    format="yyyy-MM-dd HH:mm"
                                    value-format="yyyy-MM-dd HH:mm"
                                    v-model="settingForm.startTime"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.endTime')+'：'" prop="endTime">
                                <el-date-picker
                                    type="datetime"
                                    :placeholder="$t('message.plzSelect')"
                                    style="100%"
                                    :picker-options="pickerOptions"
                                    :default-value="settingForm.startTime"
                                    format="yyyy-MM-dd HH:mm"
                                    value-format="yyyy-MM-dd HH:mm"
                                    v-model="settingForm.endTime"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item :label="$t('exempt.operation.isAble')+'：'">
                        <el-switch
                            v-model="settingForm.isEnable"
                            :active-value="0"
                            :inactive-value="1"
                            active-color="#3e82e5"
                            inactive-color="#e5e5e5"
                        ></el-switch>
                    </el-form-item>
                    <el-form-item :label="$t('message.remark')+'：'">
                        <el-input
                            type="textarea"
                            :rows="2"
                            :placeholder="$t('message.plsInput')"
                            v-model="settingForm.remark"
                        ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="handleClick('RESET')">{{$t('message.reset')}}</el-button>
                        <el-button type="primary" @click="handleClick('SAVE')">{{$t('message.save')}}</el-button>
                    </el-form-item>
                </el-form>
            </template>
            <template v-if="activeName == 'right'">
                <h1 slot="header">{{$t('exempt.operation.upload')}}</h1>
                <div class="toLine">
                    <span>{{$t('exempt.baseInfo.noStudyApplicationForm')+'：'}}</span>
                    <el-upload
                        :headers="{
                            'X-Token': $store.state.session.sessionid
                        }"
                        :data="{
                            bucketname: 'face',
                            folderpath: 'file'
                        }"
                        limit="1"
                        action="/api/commonservice/obsfile/uploadfile"
                        :on-success="handlerSuccessNS"
                        :on-remove="handlerRemoveNS"
                        :before-upload="beforeUpload"
                        :on-error="handlerError"
                        :on-preview="handlerPreNS"
                        :on-exceed="handleExceed"
                        :file-list="noStudyFileList"
                    >
                        <el-button size="small" type="primary">
                            <i class="el-icon-upload el-icon--left"></i>
                            {{$t('exempt.operation.upload')}}
                        </el-button>
                    </el-upload>
                </div>
                <div class="line"></div>
                <div class="toLine">
                    <span>{{$t('exempt.baseInfo.noListenApplicationForm')+'：'}}</span>
                    <el-upload
                        :headers="{
                            'X-Token': $store.state.session.sessionid
                        }"
                        :data="{
                            bucketname: 'face',
                            folderpath: 'file'
                        }"
                        limit="1"
                        action="/api/commonservice/obsfile/uploadfile"
                        :on-success="handlerSuccessNL"
                        :on-remove="handlerRemoveNL"
                        :before-upload="beforeUpload"
                        :on-preview="handlerPreNL"
                        :on-error="handlerError"
                        :on-exceed="handleExceed"
                        :file-list="noListenFileList"
                    >
                        <el-button size="small" type="primary">
                            <i class="el-icon-upload el-icon--left"></i>
                            {{$t('exempt.operation.upload')}}
                        </el-button>
                    </el-upload>
                </div>
            </template>
        </el-card>
    </div>
</template>
<script>
import { exSwitch, exUpload, exDeleteFile, queryTemplate } from 'common/src/api/exempt/exempt'
import UTILS from 'common/src/utils/utils'
export default {
    data() {
        return {
            activeName: 'left',
            settingForm: {
                calendarId: '',
                startTime: '',
                endTime: '',
                isEnable: 1, //0:启用，1：未启用
                remark: '',
                mode: '0' //0:查询，1新增
            },
            noStudyFileList: [],
            noListenFileList: [],
            settingFormRule: {
                calendarId: [{ required: true, message: '请选择学年学期', trigger: 'change' }],
                startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
                endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
            },
            pickerOptions: {
                disabledDate: time => {
                   return this.isEarlyThan(time)
                }
            }
        }
    },
    mounted() {
        this.requestSetting(this.settingForm)
        this.queryTemplate()
    },
    methods: {
        switchTabPane(tab, event) {
            // console.log(tab,event)
        },
        isEarlyThan(time) {
            return time.getTime() < new Date(this.settingForm.startTime).getTime();
        },
        async queryTemplate() {
            let { code, data } = await queryTemplate()
            if (code !== 200) return
            data.forEach(d => {
                if (d.templateType == 0) {
                    this.noStudyFileList.push({
                        url: d.objectKey,
                        name: d.templateName
                    })
                } else if (d.templateType == 1) {
                    this.noListenFileList.push({
                        url: d.objectKey,
                        name: d.templateName
                    })
                }
            })
        },
        handleClick(mode) {
            switch (mode) {
                case 'SAVE':
                    this.$refs['settingForm'].validate(valid => {
                        if (valid) {
                            this.requestSetting(Object.assign(this.settingForm, { mode: '1' }))
                        } else {
                            return false
                        }
                    })
                    break
                case 'RESET':
                    this.$refs['settingForm'].resetFields()
                    for (let key in this.settingForm) {
                        if (key == 'isEnable') {
                            this.settingForm[key] = 1
                        } else if (key == 'mode') {
                            this.settingForm[key] = '1'
                        } else {
                            this.settingForm[key] = ''
                        }
                    }
                    break
            }
        },
        async requestSetting(params) {
            let { code, data } = await exSwitch(params)
            if (code == 200) {
                if (params.mode * 1 == 1) {
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    })
                } else {
                    for (let key in this.settingForm) {
                        this.settingForm[key] = data[0][key]
                    }
                }
            }
        },
        //文件超出个数限制
        handleExceed() {
            this.$message({
                message: '附件最多上传一个！',
                type: 'error'
            })
        },
        //上传文件失败回调
        handlerError(rresponse, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.rar,.zip,.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf',
                    size: '10'
                },
                this
            )
        },
        //上传文件成功回调
        handlerSuccessNS(response, file, fileList) {
            let responseCode = response.code
            if (responseCode === 200) {
                this.noStudyFileList.push({
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
                let obj = {
                    templateName: file && file.name,
                    objectKey:
                        file.response.data[file.name] && file.response.data[file.name].objectkey,
                    templateType: '0'
                }
                exUpload(obj)
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        handlerSuccessNL(response, file, fileList) {
            let responseCode = response.code
            if (responseCode === 200) {
                this.noListenFileList.push({
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
                let obj = {
                    templateName: file && file.name,
                    objectKey:
                        file.response.data[file.name] && file.response.data[file.name].objectkey,
                    templateType: '1'
                }
                exUpload(obj)
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //移除文件回调
        handlerRemoveNS(file, fileList) {
            exDeleteFile({
                objectKey: this.noStudyFileList[0].url,
                templateName: this.noStudyFileList[0].name,
                templateType: '0'
            })
            this.noStudyFileList = []
        },
        handlerRemoveNL(file, fileList) {
            exDeleteFile({
                objectKey: this.noListenFileList[0].url,
                templateName: this.noListenFileList[0].name,
                templateType: '1'
            })
            this.noListenFileList = []
        },
        handlerPreNS(file){
            window.location.href =
                "/api/commonservice/obsfile/downloadfile?objectkey=" + file.url;
        },
        handlerPreNL(file){
            window.location.href =
                "/api/commonservice/obsfile/downloadfile?objectkey=" + file.url;
        }
    }
}
</script>
<style scoped>
.toLine {
    display: flex;
    flex-direction: row;
    align-items: center;
}
.line {
    width: 100%;
    height: 0px;
    border: 2px solid #e4e4e4;
    margin: 32px 0;
}
</style>